#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/3 15:10
# @Author : 吴敬超
# explain:
import netCDF4 as nc
import time as ti
import multiprocessing
from collections import OrderedDict
import json

#
# xlen = 1047
# ylen = 1497
print ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime())
file_path_wrf = '/data1/python/nc2json/wrf_2020070700_need.nc'
file_path_roms = '/data1/python/nc2json/roms_2020070700_need.nc'

file_obj_roms = nc.Dataset(file_path_roms)
file_obj_wrf = nc.Dataset(file_path_wrf)

jsonsource = "TIME"
jsonlat = [-16.000000, 62.000000]
jsonnlat = 157
jsonlng = [39.000000, 178.000000]
jsonnlng = 279

ocean_time = file_obj_roms.variables['ocean_time']

ocean_times = nc.num2date(ocean_time[:], ocean_time.units)

romsu = file_obj_roms.variables['u'][:]
romsv = file_obj_roms.variables['v'][:]
romstemp = file_obj_roms.variables['temp'][:]
romszeta = file_obj_roms.variables['zeta'][:]
wrfRAINNC = file_obj_wrf.variables['RAINNC'][:]
wrft2 = file_obj_wrf.variables['T2'][:]
wrfolr = file_obj_wrf.variables['OLR'][:]
wrfwu = file_obj_wrf.variables['U10'][:]
wrfwv = file_obj_wrf.variables['V10'][:]


def filechanger(threadName, timenum):
    print "thread start Name is " + str(threadName)
    video = OrderedDict()

    video["source"] = jsonsource
    video["lat"] = jsonlat
    video["nlat"] = jsonnlat
    video["lng"] = jsonlng
    video["nlng"] = jsonnlng
    video["time"] = ocean_times[timenum].strftime("%Y-%m-%d_%H:%M:%S")

    video["u"] = romsu[timenum][0].flatten().tolist()
    video["v"] = romsv[timenum][0].flatten().tolist()
    video["temp"] = romstemp[timenum][0].flatten().tolist()
    video["zeta"] = romszeta[timenum].flatten().tolist()
    video["rain"] = wrfRAINNC[timenum].flatten().tolist()
    video["t2"] = wrft2[timenum].flatten().tolist()
    video["olr"] = wrfolr[timenum].flatten().tolist()
    video["wu"] = wrfwu[timenum].flatten().tolist()
    video["wv"] = wrfwv[timenum].flatten().tolist()
    ffpath = "/data1/python/jsonfile/"

    # json_str = json.dumps(video)
    # print json_str
    # json_str = json.dumps(video)
    # print json_str
    # crcm1.json
    filename = ffpath + "crcm" + str(timenum) + ".json"

    with open(filename, "w") as f:
        json.dump(video, f)
    #
    # with open('videotest_datan.json', 'w') as json_file:
    #     json_file.write(json_str)

    # print ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime())
    print "thread end Name is" + str(threadName)

    print "%s: %s" % (threadName, ti.ctime(ti.time()))


if __name__ == "__main__":
    # print("main")

    print ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime())

    pool = multiprocessing.Pool(processes=8)
    for timenum in range(0, len(ocean_times), 6):
        Threadname = "process-" + str(timenum)

        pool.apply_async(filechanger, (Threadname, timenum,))

    pool.close()
    pool.join()

    print ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime())
